from datetime import datetime
from core.celery import celery_app, TaskMonitor
from app.celery_task.models.celery_task import CeleryTask
from app.monitor_metrics.handlers.prom_alarm_template_handler import PromAlarmTemplateHandler
from app.monitor_metrics.handlers.prom_host_group_handler import PromHostGroupHandler
from common.database import SessionLocal
from common.welab_k8s import init_k8s

from core.logger import logger


@celery_app.task(bind=True)
def watch_dog(self):
    """
    celery异步任务的监控
    """
    session = SessionLocal()
    task_name = self.name.split(".")[-1]

    object = CeleryTask.get_object_by_name(session, task_name)
    if not object:
        # 如果不存在，则添加
        task_id = self.request.id
        type = self.name.split(".")[1]
        comment = f"{task_name} begin"
        task_data = {
            "name": task_name,
            "type": type,
            "tid": task_id,
            "relation_uuid": 0,
            "state": "SUCCESS",
            "progress": 100,
            "start_at": datetime.now(),
            "comment": comment
        }
        result = CeleryTask.add(session, task_data)
        if not result:
            logger.error(f"task_name:{task_name} task_id:{task_id}, add task failed")
            return False

        logger.info(f"task_name:{task_name} task_id:{task_id}, add task success")
    else:
        # 如果存在，则更新
        CeleryTask.update_task(session, object.tid)
        logger.info(f"{task_name} update success")

    return True



@celery_app.task(base=TaskMonitor, bind=True)
def prom_update_alarm_template_async(self, data):
    """
    更新告警模板的异步任务
    """
    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()
    init_k8s()

    # 开始更新告警模板
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        prom_alarm_template_handler = PromAlarmTemplateHandler()
        result = prom_alarm_template_handler.task_update_alarm_template_handle(session, data)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True



@celery_app.task(base=TaskMonitor, bind=True)
def prom_host_group_bind_template_async(self, data):
    """
    主机组绑定模板的异步任务
    """
    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()
    init_k8s()

    # 开始更新告警模板
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        prom_host_group_handler = PromHostGroupHandler()
        result = prom_host_group_handler.task_bind_template_handle(session, data)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True




@celery_app.task(base=TaskMonitor, bind=True)
def prom_host_group_unbound_template_async(self, data):
    """
    主机组解绑模板的异步任务
    """
    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()
    init_k8s()

    # 开始更新告警模板
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        prom_host_group_handler = PromHostGroupHandler()
        result = prom_host_group_handler.task_unbound_template_handle(session, data)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True



@celery_app.task(base=TaskMonitor, bind=True)
def prom_host_group_update_notice_async(self, data):
    """
    主机组更新通知人的异步任务
    """
    # 获取任务信息
    tid = self.request.id
    session = SessionLocal()
    task_name = self.name.split(".")[-1]
    init_k8s()

    # 开始更新告警模板
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        prom_host_group_handler = PromHostGroupHandler()
        result = prom_host_group_handler.task_update_notice_handle(session, data)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True



if __name__ == '__main__':
    pass
